package com.example.demo.filter;

import com.example.demo.domin.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.security.UserAuthentication;
import com.example.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter{

    @Resource
    UserMapper userMapper;

    @Resource
    HandlerExceptionResolver handlerExceptionResolver;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.equals("/user/signUp") || uri.equals("/user/login")){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Authorization");
       if (token==null){
           handlerExceptionResolver.resolveException(request,response,null,new IllegalArgumentException("未携带token,请重新登录"));
           return;
       }
        Claims claims = JwtUtil.getClaims(token);
        Long id = (Long) claims.get("userId");
        User user = userMapper.selectById(id);
        UserAuthentication authentication = new UserAuthentication(user.getUsername(), user.getPassword());
        authentication.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);
    }
}
